import axios from "axios";
import { message } from "antd";
export default class PromiseAxios {

  //封装 ajax
  static ajax(options) {
    //axios 触发loading动画
    let loading;
    if(options.data&&options.data.isShowLoading !== false){
        loading = document.getElementById('ajaxLoading');
        loading.style.display="block";
    }
    //设置默认api
    let baseApi = "";
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    if (options.isMoke) {
      //如果是ture 用 moke假数据
      baseApi = "https://www.easy-mock.com/mock/5c4961cb28a69b32a72d2c1b/testmock";
    } else {
      //如果false , 用实际地址
      baseApi = "";
    }
    //默认post
    let method = options.method || "post";
    return new Promise((resolve, reject) => {
      axios({
        url: options.url,
        method:method,
        baseURL: baseApi,
        timeout: 5000,
        params: (options.data && options.data.params) || ""
      }).then(response => {
        //如果返回数据就关闭loading动画
        if(options.data&&options.data.isShowLoading !==false){
            loading = document.getElementById('ajaxLoading');
            loading.style.display="none";
        }
        if (response.status == "200") {
          //code是后端自己设置的
          if (response.data.code == "0") {
            resolve(response.data);
          } else {
            message.error(response.data.msg)
          }
        } else {
          reject(response.data);
        }
      });
    });
  }
}
